package com.xjoyt.pay.controllers.seabluesky;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.xjoyt.pay.controllers.AbstractController;
import com.xjoyt.pay.dto.CallbackResult;
import com.xjoyt.pay.dto.MerchantChannelRegister;
import com.xjoyt.pay.dto.OrderUrlResult;
import com.xjoyt.pay.dto.params.CallbackParam;
import com.xjoyt.pay.dto.params.MerchantRateRegister;
import com.xjoyt.pay.dto.params.OrderAdapterParam;
import com.xjoyt.pay.po.HtmlPage;
import com.xjoyt.pay.repository.HtmlPageRepository;
import com.xjoyt.pay.util.FormDateReportConvertor;
import com.xjoyt.pay.util.HttpClientUtil;
import com.xjoyt.pay.util.MD5Facade;
import com.xjoyt.pay.util.ToFormString;
import com.xjoyt.pay.vo.Order;

/**
 * demo适配器
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("seaBlueSky/wapPay")
public class WapPayController extends AbstractController {

	private final static String sendURL = "https://pay.ipaynow.cn/";

	@Autowired
	private HtmlPageRepository htmlPageRepository;

	/**
	 * 商户进件
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("register")
	public MerchantChannelRegister register(@RequestBody MerchantRateRegister param) {
		System.out.println("aaaaaaaaaa");
		MerchantChannelRegister result = new MerchantChannelRegister();
		result.no = "123";
		result.key = "abc";
		return result;
	}

	/**
	 * 微信wap 向上游发起订单，前置条件订单信息已验证、订单已保存
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("wechatWap")
	public OrderUrlResult wechatWap(String no, String key, @RequestBody OrderAdapterParam param,
			HttpServletRequest request) {

		OrderUrlResult orderUrlResult = new OrderUrlResult();

		Map<String, String> dataMap = new HashMap<String, String>();
		// TODO 项目地址待定
		String return_url = param.order.orderConfig.successUrl;// 同步通知地址（替换成平台的）
		String notify_url = param.order.orderConfig.notifyUrl;// 现在支付回调地址
		// 根据订单号更新订单的支付方式方式
		// 商户自己的订单数据

		String appId = no;// 商户标示
		String appKey = key;// 商户密匙
		String mhtOrderNo = param.order.no;
		String mhtOrderName = param.param.body;
		String mhtOrderAmt = param.order.money + "";// 交易金额;//单位(人民币)：分整数，无小数点
		String mhtOrderDetail = param.param.detail;// 订单描述

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String mhtOrderStartTime = dateFormat.format(new Date());
		String notifyUrl = notify_url;
		String frontNotifyUrl = return_url;
		String mhtCurrencyType = "156";// 定值156（人民币 商户订单币种类型
		String version = "1.0.0";// 接口版本号定值：1.0.0
		String mhtOrderType = "01";// 消费类型 01普通消费类型
		String funcode = "WP001";// 功能码 定值：WP001
		String deviceType = "0601";// 设备类型
		String mhtCharset = "UTF-8";// 商户字符编码
		String payChannelType = "13";// 微信WAP通道
		String outputType = "2";

		// String mhtReserved = req.getParameter("mhtReserved");//此参数可以不传输
		String mhtSignType = "MD5";
		dataMap.put("appId", appId);
		dataMap.put("deviceType", deviceType);
		dataMap.put("funcode", funcode);
		dataMap.put("mhtOrderNo", mhtOrderNo);
		dataMap.put("mhtOrderName", mhtOrderName);
		dataMap.put("version", version);
		dataMap.put("mhtCurrencyType", mhtCurrencyType);
		dataMap.put("mhtOrderAmt", mhtOrderAmt);
		dataMap.put("mhtOrderDetail", mhtOrderDetail);
		dataMap.put("mhtOrderType", mhtOrderType);
		dataMap.put("mhtOrderStartTime", mhtOrderStartTime);
		dataMap.put("notifyUrl", notifyUrl);
		dataMap.put("frontNotifyUrl", frontNotifyUrl);
		dataMap.put("mhtCharset", mhtCharset);
		dataMap.put("outputType", outputType);
		dataMap.put("payChannelType", payChannelType);
		dataMap.put("mhtSignType", mhtSignType);
		try {
			String mhtSignature = MD5Facade.getFormDataParamMD5(dataMap, appKey, "UTF-8");

			dataMap.put("mhtSignature", mhtSignature);
			String result = HttpClientUtil.sendPost(sendURL, dataMap);

			if (result != null) {
				Map<String, String> dataResMap = FormDateReportConvertor.parseFormDataPatternReportWithDecode(result,
						"UTF-8", "UTF-8");
				String responseCode = dataResMap.get("responseCode");
				if ("A001".equals(responseCode)) {
					String tn = dataResMap.get("tn");

					if (tn != null) {
						tn = URLDecoder.decode(tn, "utf-8");
						System.out.println("解码后的TN是===" + tn);
						Map<String, String> datarRel = FormDateReportConvertor.parseFormDataPatternReport(tn);
						String prepayid = datarRel.get("weixin://wap/pay?prepayid");
						datarRel.remove("weixin://wap/pay?prepayid");
						datarRel.put("prepayid", prepayid);
						String resp = ToFormString.buildRequest(datarRel, "GET", "submitButton");// 能生成二维码的地址
						HtmlPage htmlPage = new HtmlPage();
						htmlPage.html = resp;
						htmlPage.expireTime = LocalDateTime.now();
						htmlPage.expireTime = htmlPage.expireTime.plusSeconds(300L);
						htmlPage = htmlPageRepository.save(htmlPage);
						orderUrlResult.success = true;
						orderUrlResult.url = getBaseUrl() + "/seaBlueSky/wapPay/wechatPay/" + htmlPage.id;
						return orderUrlResult;
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		orderUrlResult.success = false;
		return orderUrlResult;
	}

	/**
	 * 支付宝wap向上游发起订单，前置条件订单信息已验证、订单已保存
	 * 
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "aliWap", method = RequestMethod.POST)
	public OrderUrlResult aliWap(String no, String key, @RequestBody OrderAdapterParam param) {
		OrderUrlResult orderUrlResult = new OrderUrlResult();

		Map<String, String> dataMap = new HashMap<String, String>();
		// TODO 项目地址待定
		String return_url = param.order.orderConfig.successUrl;// 同步通知地址（替换成平台的）
		String notify_url = param.order.orderConfig.notifyUrl;// 现在支付回调地址
		// 根据订单号更新订单的支付方式方式
		// 商户自己的订单数据
		String appId = no;// 商户标示
		String appKey = key;// 商户密匙
		String mhtOrderNo = param.order.no;
		String mhtOrderName = param.param.body;
		String mhtOrderAmt = param.order.money + "";// 交易金额;//单位(人民币)：分整数，无小数点
		String mhtOrderDetail = param.param.detail;// 订单描述
		String notifyUrl = notify_url;
		String frontNotifyUrl = return_url;

		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String mhtOrderStartTime = dateFormat.format(new Date());
		String mhtCurrencyType = "156";// 定值156（人民币 商户订单币种类型
		String mhtOrderType = "01";// 消费类型 01普通消费类型
		String version = "1.0.0";// 接口版本号定值：1.0.0
		String funcode = "WP001";// 功能码 定值：WP001
		String deviceType = "0601";// 设备类型
		String mhtCharset = "UTF-8";// 商户字符编码
		String payChannelType = "12";// 微信WAP通道
		String outputType = "0";

		// String mhtReserved = req.getParameter("mhtReserved");//此参数可以不传输
		String mhtSignType = "MD5";
		dataMap.put("appId", appId);
		dataMap.put("deviceType", deviceType);
		dataMap.put("funcode", funcode);
		dataMap.put("mhtOrderNo", mhtOrderNo);
		dataMap.put("mhtOrderName", mhtOrderName);
		dataMap.put("version", version);
		dataMap.put("mhtCurrencyType", mhtCurrencyType);
		dataMap.put("mhtOrderAmt", mhtOrderAmt);
		dataMap.put("mhtOrderDetail", mhtOrderDetail);
		dataMap.put("mhtOrderType", mhtOrderType);
		dataMap.put("mhtOrderStartTime", mhtOrderStartTime);
		dataMap.put("notifyUrl", notifyUrl);
		dataMap.put("frontNotifyUrl", frontNotifyUrl);
		dataMap.put("mhtCharset", mhtCharset);
		dataMap.put("outputType", outputType);
		dataMap.put("payChannelType", payChannelType);
		dataMap.put("mhtSignType", mhtSignType);
		try {
			String mhtSignature = MD5Facade.getFormDataParamMD5(dataMap, appKey, "UTF-8");
			dataMap.put("mhtSignature", mhtSignature);
			String result = HttpClientUtil.sendPost(sendURL, dataMap);
			if (StringUtils.isEmpty(result) || !result.contains("立即支付")) {
				orderUrlResult.success = false;
				return orderUrlResult;
			}
			HtmlPage htmlPage = new HtmlPage();
			htmlPage.html = result;
			htmlPage.expireTime = LocalDateTime.now();
			htmlPage.expireTime = htmlPage.expireTime.plusSeconds(300L);
			htmlPage = htmlPageRepository.save(htmlPage);
			orderUrlResult.success = true;
			orderUrlResult.url = getBaseUrl() + "/seaBlueSky/wapPay/aliPay/" + htmlPage.id;
			return orderUrlResult;
		} catch (Exception e) {
			e.printStackTrace();
			orderUrlResult.success = false;
			return orderUrlResult;
		}
	}

	@RequestMapping("wechatPay/{id}")
	public String wechatPay(@PathVariable String id) {
		HtmlPage htmlPage = htmlPageRepository.findOne(id);
		if (htmlPage == null) {
			return "404";
		}
		return htmlPage.html;
	}

	@RequestMapping("aliPay/{id}")
	public String aliPay(@PathVariable String id) {
		HtmlPage htmlPage = htmlPageRepository.findOne(id);
		if (htmlPage == null) {
			return "404";
		}
		return htmlPage.html;
	}

	/**
	 * 回调
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("callback")
	public CallbackResult callback(String key, @RequestBody CallbackParam param) {
		CallbackResult result = new CallbackResult();
		// 上游响应
		Map<String, String> dataMap = new HashMap<>();
		if (!param.body.equals("")) {
			String code = param.body.replaceAll("&", "=");
			String[] stringArr = code.split("=");
			for (int i = 0; i < stringArr.length; i = i + 2) {
				dataMap.put(stringArr[i], stringArr[i + 1]);
			}
		}
		if (param.params != null) {
			for (Entry<String, String[]> entry : param.params.entrySet()) {
				if (entry.getValue() == null || entry.getValue().length <= 0) {
					continue;
				}
				dataMap.put(entry.getKey(), entry.getValue()[0]);
			}
		}
		result.success = false;
		result.callbackResponse = "FAIL";
		String md5Key = key;
		// 去除签名类型和签名值
		String signature = dataMap.get("signature");
		dataMap.remove("signature");
		dataMap.remove("signaType");
		boolean isValidSignature = MD5Facade.validateFormDataParamMD5(dataMap, md5Key, signature);
		// 拿到自己应用的md5Key
		String transStatus = dataMap.get("transStatus");// 交易状态
		String channelOrderNo = dataMap.get("channelOrderNo");// 渠道订单号
		if (!isValidSignature) {// 验证签名失败
			return result;
		}
		if ("A001".equals(transStatus)) {
			result.success = true;
			// 上游响应
			result.tradeNo = channelOrderNo;
			result.callbackResponse = "SUCCESS";
		}
		return result;
	}

	/**
	 * 结算状态查询
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("settlement")
	public OrderUrlResult settlement(String type, @RequestBody Order param) {
		OrderUrlResult orderUrlResult = new OrderUrlResult();
		if (!StringUtils.isEmpty(type)) {
			if (type.equals("T0")) {
				orderUrlResult.success = true;
				return orderUrlResult;
			}
		}
		orderUrlResult.success = false;
		return orderUrlResult;
	}
}
